#define _XOPEN_SOURCE
#include <func.h>
#include "head.h"
int sendUserPassWord(char *password, int sockFd);
void get_salt(char *salt, char *pwd){
    int i, j;
    for(i = 0, j = 0; pwd[i] && j != 3; ++i){
        if(pwd[i] == '$')
            ++j;
    }
    strncpy(salt, pwd, i - 1);
}
int isLegalUser(int sockFd, char *userName){
    char password[100] = {0};
    sendUserPassWord(password, sockFd);

    train_t t;
    //收到盐值
    int dataLength;
    char salt[30] = {0};
    recv(sockFd, &dataLength, sizeof(dataLength), MSG_WAITALL);
    recv(sockFd, salt, dataLength, MSG_WAITALL);

    //混合加密为密文，发送密文
    char cryptograph[500] = {0};
    strcpy(cryptograph, crypt(password, salt));
    memset(&t, 0, sizeof(train_t));
    strcpy(t.buf, cryptograph);
    t.dataLength = strlen(t.buf);
    send(sockFd, &t, sizeof(t.dataLength)+t.dataLength, MSG_NOSIGNAL);

    char res;
    recv(sockFd, &res, 1, MSG_WAITALL);
    if(res == '1'){//合法用户
        return 1;
    }else{//非法用户
        return -1;
    }
}

int userRegister(int sockFd, char *token, int fd){
    char password[100] = {0};
    sendUserPassWord(password, sockFd);

    /*收到token*/
    int dataLength;
    recv(sockFd, &dataLength, sizeof(dataLength), MSG_WAITALL);
    recv(sockFd, token, dataLength, MSG_WAITALL);

    /*存进token文件中*/
    write(fd, token, sizeof(token));

    return 0;
}

int sendUserPassWord(char *password, int sockFd){
    puts("please enter the password: ");
    char ch;
    int i = 0;
    while((ch = getchar()) != '\n'){
        password[i++] = ch;
    }
    password[i] = '\0';
    train_t t;
    strcpy(t.buf, password);
    t.dataLength = strlen(password);
    send(sockFd, &t, sizeof(t.dataLength)+t.dataLength, MSG_NOSIGNAL);
}